//
//  BNOAuthVC.swift
//  BNWeiBo
//
//  Created by ba.o0 on 16/8/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

//11.0
import UIKit
import SVProgressHUD
import AFNetworking


class BNOAuthVC: UIViewController {
    
    //12.2
    override func loadView() {
        view = webView
        // 判断url 是否为nil
        guard let url = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)")
    else{
    return
    }
    //12.4
//    webView.delegate = self
    // 实例化request
    let request = NSURLRequest(URL: url)
    // 记载 request
    webView.loadRequest(request)
    
}
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    //11.4
    //MARK: - 监听方法
    //取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    //自动填充
    @objc private func autofillAction(){
        print("自动填充")
        //12.3
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWD)'"
        // js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    //11.2
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    //11.3
    //MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofillAction")
        
        navigationItem.title = "微博登录"
    }
    //12.1
    //MARK: - 懒加载控件
    private lazy var webView:UIWebView = UIWebView()
}
//12.5
extension BNOAuthVC:UIWebViewDelegate{
    //12.6
    /*
    - 监听 webView 将要加载的request
    - 如果不实现 默认 返回true
    - 如果返回 false 停止加载reque
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 判断urlString 是否为nil 而且 它的前缀是否为我们设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            // query 请求参数
            // 判断是否为nil
            if let query = request.URL?.query{
                // 获取code(截取字符串)
                let code = query.substringFromIndex("code=".endIndex)
                print("终于等到你:\(code)")
                //12.7
                getUserAccount(code)
                
            }
        }
        return true
    }
    
    //12.5
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        //SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}

//12.6
//MARK: - 请求数据
extension BNOAuthVC{
    //获取授权
    func getUserAccount(code: String){
        //请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let  params = [
            "client_id":WBAppKey,
            "client_secret":WBAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WBRedirect_uri
        ]
        // 发送请求
        let manager = AFHTTPSessionManager()
        
        //12.8
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            print("请求成功:\(response)")
            //13.2
            // 判断response 是否为nil 而且是否可以转成一个字典
            //如果你使用if-let 或者guard 判断可选值是否可以转成我们想要的类型 一般均使用as?
            guard let res = response as? [String: AnyObject] else{
                return
            }
            
            
            //13.1
            // 通过字典创建一个模型
            let userAccount = BNUserAccountModel(dict: res)
            print(userAccount)
            
            }) { (_, error) -> Void in
                print("请求失败:\(error)")
        }
        
        
    }
    
}